<?php

namespace app\admin\controller;

use AlibabaCloud\Client\Request\Request;
use app\admin\controller\auth\Admin;
use app\admin\model\Aivideo;
use app\admin\model\AivideoCompositeLog;
use app\admin\model\SellerLog;
use app\admin\model\SellerCode;
use app\common\controller\Backend;
use Exception;
use fast\Tree;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;
use think\Session;

/**
 * 活动管理
 *
 * @icon fa fa-circle-o
 */
class Activity extends Backend
{

    /**
     * Activity模型对象
     * @var \app\admin\model\Activity
     */
    protected $model = null;
    protected  $ClientKey=null;
    protected  $ClientSecret=null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Activity;
        if (model('AuthGroupAccess')->where('uid', $this->auth->id)->value('group_id') !== get_addon_config('douyin')['store_id']) {
            $this->view->assign("is_super", true);
        }
        $this->view->assign("paytypeList", $this->model->getPaytypeList());
        $this->view->assign("redirectList", $this->model->getRedirectList());

        if (!$config = Cache::get('cdk')) {
            $data_auth = json_decode(file_get_contents('http://zk.ydk1.cn/index.php/api/token/auth'), true);
            if ($data_auth['code'] == 0) {
                $this->error($data_auth['msg']);
            }

            $config = $data_auth['data'];
            Cache::set('cdk', $config, 86400);
        }

        if(config('site.severmit')==1)
        {

            $this->ClientKey = $config['ClientKey'];
            $this->ClientSecret = $config['ClientSecret'];

        }
        else{

            $this->ClientKey = config('site.ClientKey');
            $this->ClientSecret = config('site.ClientSecret');
        }



    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($this->auth->id != get_addon_config('douyin')['super_id']) {
                $child = model('Admin')->getAgentChild($this->auth->id,'shop_id');

                if ($child) {
                    $this->model->where($this->model->getTable() . '.manystore_id','in' ,$child);
                } else {
                    $shop_id = Session::get("admin")['shop_id'];
                    if(!$shop_id) $shop_id = -1;
                    $this->model->where($this->model->getTable() . '.manystore_id', $shop_id);
                }
            }



            $list = $this->model
                ->with(['card', 'manystoreshop'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('card')->visible(['title']);
                $row->getRelation('manystoreshop')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");



            if ($params['paytype']!=2) {
                if (empty($params['card_id'])) {
                    $this->error('请添加卡卷id');
                }

                if (empty($params['scan_times'])) {
                    $this->error('请填写扫码次数');
                }
            }



            
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function poster($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $baseurl = $this->request->baseFile(true);
        $baseurl = str_replace('GwECynxtZU.php', 'index.php', $baseurl);

        $count=\app\admin\model\Aivideo::where('activity_id',$ids)->count();
        if(!$count) $this->error("该活动没创建视频,请合成视频");


        $admindata=model('Admin')->where('id',$this->auth->id)->find();

        if(config('site.severmit')==1)
        {



            if (empty($admindata->admin_subordinate)) {


                if ($admindata->id==1) {
                        $local_url="{$baseurl}/index/index/douyin/ids/{$ids}";
                        $remot_url="http://ippkk.com/index.php/api/token/getOpen?url=$local_url";
                        $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri=$remot_url";

                        $this->view->assign("url", $url);
                }else{

                    $parentdata=model('Admin')->where('id',$admindata->pid)->find();
                    if ($parentdata->admin_subordinate) {
                        if ($parentdata->douyin_type==3) {   //平台公用，代理自用

                            $remot_url="{$parentdata->agent_domain}/index.php/index/index/douyin/ids/{$ids}";
                            $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $parentdata->client_key . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri=$remot_url";

                            $this->view->assign("url", $url);


                        }else{   //平台公用，代理公用

                            $local_url="{$baseurl}/index/index/douyin/ids/{$ids}";
                            $remot_url="http://ippkk.com/index.php/api/token/getOpen?url=$local_url";
                            $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri=$remot_url";

                            $this->view->assign("url", $url);

                        }
                    }

                }

            }


        }
        else{


            if (empty($admindata->admin_subordinate)) {


                if ($admindata->id==1) {

                    $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri={$baseurl}/index/index/douyin/ids/{$ids}";
                    $this->view->assign("url", $url);

                }else{


                    $parentdata=model('Admin')->where('id',$admindata->pid)->find();
                    if ($parentdata->admin_subordinate) {
                       if ($parentdata->douyin_type==2) {

                        $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri={$parentdata->system_domain}/index.php/index/index/douyin/ids/{$ids}";

                        $this->view->assign("url", $url);


                       }else{

                            $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $parentdata->client_key . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri={$parentdata->agent_domain}/index.php/index/index/douyin/ids/{$ids}";

                            $this->view->assign("url", $url);

                       }
                    }


                }


            }


            // dump($admindata);die();


        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function seller($ids = null)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $code = (int)$this->request->post("code");
            $where['code'] = $code;
            $where['activity_id'] = $row->id;
            $m_code = new SellerCode();
            $onecode = $m_code->where($where)->find();

            if (!$onecode) {
                $this->error("未找到该核销码");
            }

            if ($onecode->status == 1) {
                $this->error("该核销码已经被核销过");
            }

            if ($onecode->status == 0) {
                $onecode->status = 1;
                $onecode->save();
                $this->success("已核销该核销码");
            }
        }

        $baseurl = $this->request->baseFile(true);
        $baseurl = str_replace('GwECynxtZU.php', 'index.php', $baseurl);


        if(config('site.severmit')==1)
        {
            $local_url="{$baseurl}/index/index/seller/ids/{$ids}";
            $remot_url="http://ippkk.com/index.php/api/token/getOpen?url=$local_url";
            $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri=$remot_url";

            $this->view->assign("url", $url);

        }else{
            $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create,data.external.item&redirect_uri={$baseurl}/index/index/seller/ids/{$ids}";

            $this->view->assign("url", $url);

        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function sellcards($ids = null)
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = Db::view('seller_code', '*')
                ->view('user', 'username,avatar', 'seller_code.user_id=user.id', 'LEFT')
                ->where('activity_id', '=', $ids)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function selluser($ids = null)
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = Db::view('seller_log', '*')
                ->view('user', 'username,avatar', 'seller_log.user_id=user.id', 'LEFT')
                ->where('activity_id', '=', $ids)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params['paytype']!=2) {
                if (empty($params['card_id'])) {
                    $this->error('请添加卡卷id');
                }

                if (empty($params['scan_times'])) {
                    $this->error('请填写扫码次数');
                }
            }




            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                if (model('AuthGroupAccess')->where('uid', $this->auth->id)->value('group_id') == get_addon_config('douyin')['store_id']) {
                    $shop_id = Session::get("admin")['shop_id'];
                    if ($shop_id) {
                        $params['manystore_id'] = $shop_id;
                    }
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    model('Admin')->where('id',$this->auth->id)->setInc('activity_nums');
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    protected function selectpage()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }

        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }
            if ($this->auth->id != get_addon_config('douyin')['super_id']) {
                $child = model('Admin')->getAgentChild($this->auth->id,'shop_id');

                if ($child) {
                    $this->model->where($this->model->getTable() . '.manystore_id','in' ,$child);
                } else {
                    $shop_id = Session::get("admin")['shop_id'];
                    if ($shop_id) {
                        $this->model->where($this->model->getTable() . '.manystore_id', $shop_id);
                    }
                }
            }
            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    public function statistics($ids = null)
    {
        $data = array();
        $data['compositeTotal'] = AivideoCompositeLog::where('activity_id', $ids)->sum('video_nums');
        $data['availableVideoTotal'] = Aivideo::where('activity_id', $ids)->where('status', 2)->count();
        $data['shareVideoTotal'] = SellerLog::where('activity_id', $ids)->where('type', 1)->count();

        $this->view->assign("data", $data);
        return $this->view->fetch();
    }

}
